package com.kai.mqtt.util;

import com.kai.mqtt.config.BrokerProperties;
import com.kai.mqtt.enums.ShareStrategyEnum;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Random;

/**
 * @author weijk
 * @since 2024/6/17
 */
@Component
public class LoadStrategyUtil {

    private static final Random RANDOM = new Random();

    private static ShareStrategyEnum strategy;

    public LoadStrategyUtil(BrokerProperties brokerProperties) {
        strategy = brokerProperties.getShareStrategy();
    }

    public static int getIndex(Integer currentIndex, Integer totalServer) {
        return switch (strategy) {
            case RANDOM -> random(totalServer);
            case POLLING -> polling(currentIndex, totalServer);
            case FIXED -> fixed(currentIndex, totalServer);
        };
    }

    private static int random(Integer totalServer) {
        return RANDOM.nextInt(totalServer);
    }

    private static int polling(Integer currentIndex, Integer totalServer) {
        if (Objects.isNull(currentIndex)) {
            currentIndex = 0;
        }

        return ++currentIndex % totalServer;
    }

    private static int fixed(Integer currentIndex, Integer totalServer) {
        return Objects.isNull(currentIndex) ? random(totalServer) : currentIndex;
    }
}
